<template>
  <div class="conversation-list-container">
    <div class="conversation-header">
      <h3>会话历史</h3>
      <el-button 
        type="primary" 
        size="small" 
        icon="el-icon-plus" 
        @click="createNewConversation"
        class="new-conversation-btn"
      >
        新建会话
      </el-button>
    </div>
    
    <div class="conversation-list">
      <div
        v-for="conversation in conversations"
        :key="conversation.id"
        class="conversation-item"
        :class="{ active: currentConversationId === conversation.id }"
        @click="selectConversation(conversation.id)"
      >
        <div class="conversation-content">
          <div class="conversation-title" :title="conversation.name">
            {{ conversation.name }}
          </div>
          <div class="conversation-preview" :title="conversation.lastMessage">
            {{ conversation.lastMessage || '暂无消息' }}
          </div>
          <div class="conversation-time">
            {{ formatTime(conversation.updated_at * 1000) }}
          </div>
        </div>
        <div class="conversation-actions">
          <el-button
            type="text"
            icon="el-icon-delete"
            size="mini"
            @click.stop="deleteConversationHandler(conversation.id)"
            class="delete-btn"
          />
        </div>
      </div>
      
      <div v-if="conversations.length === 0" class="empty-state">
        <i class="el-icon-chat-line-square"></i>
        <p>暂无会话记录</p>
        <p>点击"新建会话"开始对话</p>
      </div>
    </div>
  </div>
</template>

<script>
import { formatTime } from '@/utils/chatUtils';
import { getConversations, deleteConversation } from '@/api/dify/api_lx';

export default {
  name: 'ConversationList',
  props: {
    currentConversationId: {
      type: [String, Number],
      default: ''
    },
    userId: {
      type: String,
      default: 'user_' + Date.now()
    }
  },
  data() {
    return {
      conversations: [],
      loading: false,
      hasLoaded: false // 标记是否已经加载过，避免重复加载
    }
  },
  watch: {
    // 监听 userId 变化，当 userId 从空变为有值时，自动加载会话列表（作为父组件调用失败时的备选）
    userId: {
      handler(newUserId, oldUserId) {
        // 只有当 userId 从空值变为有值，且还未加载过时，才自动加载
        if (newUserId && (!oldUserId || oldUserId === '') && !this.hasLoaded) {
          console.log('👤 userId 已设置（通过 watch），开始加载会话列表:', newUserId);
          this.loadConversations();
          this.hasLoaded = true;
        }
      }
    }
  },
  mounted() {
    // mounted 时如果 userId 已经有值，则加载会话列表（用于父组件同步传入的情况）
    if (this.userId && this.userId !== 'user_' + Date.now() && !this.hasLoaded) {
      console.log('👤 mounted 时 userId 已有值，开始加载会话列表:', this.userId);
      this.loadConversations();
      this.hasLoaded = true;
    }
  },
  methods: {
    formatTime,
    
    // 加载会话列表
    async loadConversations() {
      // 如果 userId 为空或无效，不执行加载
      if (!this.userId || this.userId === 'user_' + Date.now()) {
        console.warn('⚠️ userId 无效，跳过加载会话列表:', this.userId);
        return;
      }
      
      this.loading = true;
      try {
        console.log('📥 开始加载会话列表，用户ID:', this.userId);
        const result = await getConversations(this.userId, 50);
        //console.log('API响应结果:', result);
        
        if (result.success) {
          this.conversations = result.data || [];
          //console.log('📥 加载的会话列表:', this.conversations);
        } else {
          throw new Error(result.error || '获取会话列表失败');
        }
      } catch (error) {
        console.error('加载会话列表失败:', error);
        
        // 根据错误类型显示不同的提示信息
        let errorMessage = '加载会话列表失败';
        const errorMsg = error.message || '';
        
        if (errorMsg.includes('API认证失败') || errorMsg.includes('unauthorized')) {
          errorMessage = 'API认证失败，请检查Dify配置';
        } else if (errorMsg.includes('timeout') || errorMsg.includes('超时')) {
          errorMessage = '请求超时，请稍后重试';
        } else if (errorMsg.includes('network') || errorMsg.includes('网络')) {
          errorMessage = '网络连接失败，请检查网络';
        } else if (errorMsg.includes('API密钥未配置')) {
          errorMessage = 'Dify API密钥未配置，请联系管理员';
        } else if (errorMsg.includes('API地址未配置')) {
          errorMessage = 'Dify API地址未配置，请联系管理员';
        } else {
          errorMessage = '加载会话列表失败：' + errorMsg;
        }
        
        this.$message.error(errorMessage);
        this.conversations = [];
      } finally {
        this.loading = false;
      }
    },
    
    // 创建新会话
    createNewConversation() {
      console.log('🆕 创建新会话');
      const newConversation = {
        id: '', // Dify API 会自动生成
        name: '新对话',
        inputs: {},
        status: 'normal',
        created_at: Math.floor(Date.now() / 1000),
        updated_at: Math.floor(Date.now() / 1000)
      };
      
      //console.log('📤 发送新会话事件:', newConversation);
      // 通知父组件切换到新会话
      this.$emit('conversation-selected', newConversation);
    },
    
    // 选择会话
    selectConversation(conversationId) {
      const conversation = this.conversations.find(c => c.id === conversationId);
      if (conversation) {
        this.$emit('conversation-selected', conversation);
      }
    },
    
    // 删除会话
    async deleteConversationHandler(conversationId) {
      try {
        await this.$confirm('确定要删除这个会话吗？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        });
        
        const result = await deleteConversation(conversationId, this.userId);
        if (result.success) {
          // 如果删除的是当前会话，切换到第一个会话或创建新会话
          if (conversationId === this.currentConversationId) {
            if (this.conversations.length > 1) {
              const remainingConversations = this.conversations.filter(c => c.id !== conversationId);
              this.selectConversation(remainingConversations[0].id);
            } else {
              this.createNewConversation();
            }
          }
          
          // 重新加载会话列表
          await this.loadConversations();
          this.$message.success('会话已删除');
        } else {
          throw new Error(result.error || '删除会话失败');
        }
      } catch (error) {
        if (error !== 'cancel') {
          console.error('删除会话失败:', error);
          this.$message.error('删除会话失败：' + (error.message || '未知错误'));
        }
      }
    },
    
    // 更新会话（用于本地状态更新）
    updateConversation(conversationId, updates) {
      const conversation = this.conversations.find(c => c.id === conversationId);
      if (conversation) {
        Object.assign(conversation, updates);
        conversation.updated_at = Math.floor(Date.now() / 1000);
      }
    },
    
    // 添加消息到会话（用于本地状态更新）
    addMessageToConversation(conversationId, message) {
      const conversation = this.conversations.find(c => c.id === conversationId);
      if (conversation) {
        conversation.updated_at = Math.floor(Date.now() / 1000);
        
        // 如果消息是第一条用户消息，更新会话名称
        if (message.is_from_self && message.content) {
          conversation.name = message.content.length > 20 
            ? message.content.substring(0, 20) + '...' 
            : message.content;
        }
      }
    },
    
    // 添加新会话到列表
    addNewConversation(conversation) {
      console.log('📝 添加新会话到列表:', conversation);
      
      // 检查是否已存在相同ID的会话
      const existingIndex = this.conversations.findIndex(c => c.id === conversation.id);
      if (existingIndex !== -1) {
        // 更新已存在的会话
        this.$set(this.conversations, existingIndex, conversation);
        //console.log('🔄 更新已存在的会话');
      } else {
        // 添加新会话到列表顶部
        this.conversations.unshift(conversation);
        console.log('➕ 添加新会话到列表顶部');
      }
    },
    
    /**
     * 更新会话ID
     * @param oldId 旧ID
     * @param newId 新ID
     * @param conversation 更新后的会话对象
     */
    updateConversationId(oldId, newId, conversation) {
      //console.log('🔄 更新会话ID:', oldId, '->', newId);
      const index = this.conversations.findIndex(c => c.id === oldId);
      if (index !== -1) {
        // 更新会话对象
        this.$set(this.conversations, index, conversation);
        //console.log('✅ 会话ID更新成功');
      } else {
        console.warn('⚠️ 未找到要更新的会话:', oldId);
      }
    },
    
    // 生成唯一ID（保留用于兼容性）
    generateId() {
      return 'conv_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9);
    }
  }
}
</script>

<style scoped>
.conversation-list-container {
  background: #fff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  height: calc(100vh - 200px);
  display: flex;
  flex-direction: column;
}

.conversation-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  padding-bottom: 12px;
  border-bottom: 1px solid #f0f0f0;
}

.conversation-header h3 {
  margin: 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.new-conversation-btn {
  padding: 6px 12px;
  font-size: 12px;
}

.conversation-list {
  flex: 1;
  overflow-y: auto;
}

.conversation-item {
  display: flex;
  align-items: center;
  padding: 12px;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
  margin-bottom: 8px;
  border: 1px solid transparent;
}

.conversation-item:hover {
  background-color: #f5f5f5;
}

.conversation-item.active {
  background-color: #e6f7ff;
  border-color: #1890ff;
}

.conversation-content {
  flex: 1;
  min-width: 0;
}

.conversation-title {
  font-size: 14px;
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-preview {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

.conversation-time {
  font-size: 11px;
  color: #999;
}

.conversation-actions {
  margin-left: 8px;
  opacity: 0;
  transition: opacity 0.2s;
}

.conversation-item:hover .conversation-actions {
  opacity: 1;
}

.delete-btn {
  color: #ff4d4f;
  padding: 4px;
}

.delete-btn:hover {
  background-color: #fff2f0;
}

.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
}

.empty-state i {
  font-size: 48px;
  margin-bottom: 16px;
  color: #d9d9d9;
}

.empty-state p {
  margin: 8px 0;
  font-size: 14px;
}

/* 滚动条样式 */
.conversation-list::-webkit-scrollbar {
  width: 4px;
}

.conversation-list::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 2px;
}

.conversation-list::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 2px;
}

.conversation-list::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>
